/**
 * 
 */
package org.mips.Sirius.provider.SIRI;

import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.mips.Sirius.provider.ProviderConnection;
import org.mips.Sirius.provider.ProviderException;
import org.xmlpull.v1.XmlSerializer;

import android.util.Log;
import android.util.Xml;

/**
 * @author mips
 * 
 */
public class SIRILinesRequest {

	String requestorRef;
	String linesRequest;

	public SIRILinesRequest(String requestorRef) throws ProviderException {
		this.requestorRef = requestorRef;

		createRequest();
	}

	private void createRequest() throws ProviderException {

		linesRequest = "";

		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);

			serializer.startTag("", "Siri");
			serializer.attribute("", "xmlns", "http://www.siri.org.uk/");
			serializer.attribute("", "xmlns:xsi",
					"http://www.w3.org/2001/XMLSchema-instance");
			serializer.attribute("", "xsi:schemaLocation",
					"http://www.siri.org.uk/..\\siri.xsd");
			serializer.attribute("", "version", "1.0");

			serializer.startTag("", "LinesRequest");
			serializer.attribute("", "version", "1.0");

			serializer.startTag("", "RequestTimestamp");

			DateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd'T'hh:mm:ssZ");
			Date date = new Date();
			serializer.text(dateFormat.format(date));

			serializer.endTag("", "RequestTimestamp");

			serializer.startTag("", "RequestorRef");
			serializer.text(requestorRef);
			serializer.endTag("", "RequestorRef");

			serializer.endTag("", "LinesRequest");

			serializer.endTag("", "Siri");

			serializer.endDocument();

			linesRequest = writer.toString();
		} catch (Exception e) {
			Log.d("debug", "Couldn't create a LinesRequest: " + e.getMessage());
			throw new ProviderException(e, "Couldn't create LinesRequest");
		}

		Log.d("debug", "LinesRequest created: " + linesRequest);
	}

	public SIRILinesDelivery send(ProviderConnection connection)
			throws ProviderException {

		String linesDelivery = connection.send(linesRequest);

		Log.d("debug", "LinesDelivery received: " + linesDelivery);

		return new SIRILinesDelivery(linesDelivery);
	}

}
